﻿//Oscar, Sahaj

using System.Web.Mvc;
using System.Collections.Generic;
using FacebookLoginButton.Models;
using Facebook;
using Newtonsoft.Json;

namespace FacebookLoginButton.Controllers
{
    public class AccountController : Controller
    {
        FacebookUser facebookUser;
        [HttpPost]
        public JsonResult FacebookLogin(FacebookLoginModel model)
        {
            Session["uid"] = model.uid;
            Session["accessToken"] = model.accessToken;

            return Json(new { success = true });
        }

        [HttpGet]
        public ActionResult UserDetails()
        {
            var client = new FacebookClient(Session["accessToken"].ToString());
            dynamic fbresult = client.Get("me?fields=id,name,email,first_name,last_name,gender,locale,link,username,timezone,location,picture");
            FacebookUser facebookUser = JsonConvert.DeserializeObject<FacebookUser>(fbresult.ToString());
            
            fbresult = client.Get("me/friends");
            var data = fbresult["data"].ToString();
            facebookUser.friendsList = JsonConvert.DeserializeObject<ICollection<FacebookUser>>(data);

            for (int i = 0; i < facebookUser.friendsList.Count; i++)//var friend in facebookUser.friendsList)
            {
                FacebookUser friend = facebookUser.friendsList[i];
                fbresult = client.Get(friend.id + "?fields=id,name,first_name,last_name,gender,locale,link,username,picture");
                facebookUser.friendsList[i] = JsonConvert.DeserializeObject<FacebookUser>(fbresult.ToString());
            }

            return View(facebookUser);
        }
    }
}